package com.wbao.dianniu.ui;

import java.io.File;
import java.util.ArrayList;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadTask;
import com.alibaba.sdk.android.media.utils.FailReason;
import com.alibaba.sdk.android.media.utils.StringUtils;
import com.arlen.photo.photopickup.presenter.HeadPresenter;
import com.arlen.photo.photopickup.util.FileSizeUtil;
import com.bumptech.glide.Glide;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.data.TwoAuthDetailData;
import com.wbao.dianniu.listener.IIndustryAuthListener;
import com.wbao.dianniu.listener.ITwoAuthDetailListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.IndustryAuthManager;
import com.wbao.dianniu.manager.TwoAuthDetailManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 行业认证
 * 
 * @author yejianjun
 *
 */
public class IndustryAuthActivity extends BaseActivity implements IIndustryAuthListener,ITwoAuthDetailListener {

	private TwoAuthDetailManager dManger;
	private ImageView faceButton;
	private ImageView backButton;
	private ImageView otherButton;
	private Button submitBtn;
	private TextView seeSampleTV;
	private IndustryAuthManager manager;
	private String idBeforePic;
	private String idAfterPic;
	private String industryPic;
	private Dialog dialog;
	private Button photoBtn;
	private Button choosePicBtn;
	private Button cancel_dialog;
	private final int IMAGE_OPEN = 1; // 打开图片标记
	private final int TAKE_PHOTO = 2; // 打开图片标记
	private int type;
	/** 初始状态 */
	private final int STATUS_INIT = 0; 
	/** 待审批 */
	private final int STATUS_PENDING = 1;
	/** 审批通过 */
	private final int STATUS_PASS = 2;
	/** 审批不通过 */
	private final int STATUS_NO_PASS = 3;
	private int status = STATUS_INIT;
	private boolean isClick = false;
	private Integer Id = 0;
	private Dialog pDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentLayout(R.layout.activity_industry_auth, LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
		setTitleName(getResources().getString(R.string.industry_certification));
		initBaseView();
		manager= new IndustryAuthManager(this);
		manager.addIndustryAuthListener(this);
		dManger = new TwoAuthDetailManager(this);
		dManger.addTwoAuthDetailListener(this);
		dManger.twoAuthDetail(GlobalContext.accountId);
	}
	

	private void initBaseView() {
		faceButton = (ImageView) findViewById(R.id.imageButton_ID_face);
		backButton = (ImageView) findViewById(R.id.imageButton_ID_back);
		otherButton = (ImageView) findViewById(R.id.imageButton_other);
		submitBtn = (Button) findViewById(R.id.two_auth_submit);
		seeSampleTV = (TextView) findViewById(R.id.see_sample);

		faceButton.setOnClickListener(this);
		backButton.setOnClickListener(this);
		otherButton.setOnClickListener(this);
		submitBtn.setOnClickListener(this);
		seeSampleTV.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.imageButton_ID_face:
			if(STATUS_INIT == status || STATUS_NO_PASS == status){
				type = 1;
				showRealase();
			}else if(STATUS_PENDING == status || STATUS_PASS == status){
				ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(idBeforePic);
				imageBrower(0, imageUrls);
			}
			break;
		case R.id.imageButton_ID_back:
			if(STATUS_INIT == status || STATUS_NO_PASS == status){
				type = 2 ;
				showRealase();
			}else if(STATUS_PENDING == status || STATUS_PASS == status){
				ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(idAfterPic);
				imageBrower(0, imageUrls);
			}
			break;
		case R.id.imageButton_other:
			if(STATUS_INIT == status || STATUS_NO_PASS == status){
				type = 3;
				showRealase();
			}else if(STATUS_PENDING == status || STATUS_PASS == status){
				ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(industryPic);
				imageBrower(0, imageUrls);
			}
			break;
		case R.id.btn_cancel:
			if (null != dialog && dialog.isShowing()) {
				dialog.dismiss();
			}
			break;
		case R.id.btn_take_photo:
			if (null != dialog && dialog.isShowing()) {
				dialog.dismiss();
			}
			//拍照
			 Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			 takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),"temp.jpg")));
			 startActivityForResult(takeIntent, TAKE_PHOTO);
			break;
		case R.id.btn_pick_photo:
			if (null != dialog && dialog.isShowing()) {
				dialog.dismiss();
			}
			//选择图片
			Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(intent, IMAGE_OPEN);
			break;
		case R.id.see_sample:
			Intent sampleIntent = new Intent();
			sampleIntent.setClass(IndustryAuthActivity.this, IndustrySampleActivity.class);
			startActivity(sampleIntent);
			break;
		case R.id.two_auth_submit:
			if(TextUtils.isEmpty(idBeforePic)){
				Notification.toast(IndustryAuthActivity.this, "请上传身份证正面图");
				return;
			}else if(TextUtils.isEmpty(idAfterPic)){
				Notification.toast(IndustryAuthActivity.this, "请上传身份证反面图");
				return;
			}else if(TextUtils.isEmpty(industryPic)){
				Notification.toast(IndustryAuthActivity.this, "请上传行业截图");
				return;
			}
			if(STATUS_INIT == status || STATUS_NO_PASS == status){
				if(!isClick){
					isClick = true;
					manager.auth(Id,GlobalContext.accountId, idBeforePic, idAfterPic, industryPic);
				}
			}else{
				Notification.toast(this, "已经提交申请，不能重复提交");
			}
			break;
			
		default:
			break;
		}

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		//打开图片  
        if(resultCode==RESULT_OK && requestCode==IMAGE_OPEN) {
        	System.out.println("a:" + System.currentTimeMillis());
            Uri uri = data.getData();  
            if (!TextUtils.isEmpty(uri.getAuthority())) {  
                //查询选择图片  
                Cursor cursor = getContentResolver().query( uri,   new String[] { MediaStore.Images.Media.DATA },  
                        null, null, null);  
                //返回 没找到选择图片  
                if (null == cursor) {
                    return;  
                }  
                System.out.println("b:" + System.currentTimeMillis());
                //光标移动至开头 获取图片路径  
                cursor.moveToFirst();  
                String pathImage = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); 
                cursor.close(); 
                System.out.println("c:" + System.currentTimeMillis());
                pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
                pDialog.setCancelable(false);
    			pDialog.show();
    			System.out.println("d:" + System.currentTimeMillis());
    			//图片选择成功，上传图片到cdn，得到cdn的路径
    			String fileName = "image_" + StringUtils.getUUID();
                HeadPresenter presenter = new HeadPresenter(IndustryAuthActivity.this);
                presenter.addUploadListener(new MyuploadLister(type,fileName,pathImage));
                System.out.println("e:" + System.currentTimeMillis());
                presenter.uploadImageUrl( pathImage, fileName);
                System.out.println("f:" + System.currentTimeMillis());
               /* System.out.println("pathImage:" + pathImage);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2;//图片宽高都为原来的二分之一，即图片为原来的四分之一
                options.inTempStorage = new byte[100 * 1024];
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                options.inPurgeable = true;
                options.inInputShareable = true; 
                //图片选择成功，上传图片到cdn，得到cdn的路径
                String fileName = "image_" + StringUtils.getUUID();
                PictureDownloadUtils.getInstance().zipUpload(new File(pathImage), fileName,true);*/
//                if(1 == type){
//                	 idBeforePic = fileName;
//                	 Bitmap b = FileSizeUtil.compressBitmap(pathImage, faceButton.getWidth(), faceButton.getHeight());
//                	  faceButton.setImageBitmap(b);
//				 }else if(2 == type){
//					 idAfterPic = fileName;
//					  Bitmap b = FileSizeUtil.compressBitmap(pathImage, backButton.getWidth(), backButton.getHeight());
//					  backButton.setImageBitmap(b);
//				 }else if(3 == type){
//					 industryPic = fileName;
//					 Bitmap b = FileSizeUtil.compressBitmap(pathImage, otherButton.getWidth(), otherButton.getHeight());
//					 otherButton.setImageBitmap(b);
//				 }
                System.out.println("g:" + System.currentTimeMillis());
            }
        } else if(resultCode==RESULT_OK && requestCode==TAKE_PHOTO){
        	 File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
			 //图片选择成功，上传图片到cdn，得到cdn的路径
			String fileName = "image_" + StringUtils.getUUID();
			
			  pDialog = LoadingWaitDialog.createLoadingDialog(this, "");
              pDialog.setCancelable(false);
  			  pDialog.show();
  			//图片选择成功，上传图片到cdn，得到cdn的路径
              HeadPresenter presenter = new HeadPresenter(IndustryAuthActivity.this);
              presenter.addUploadListener(new MyuploadLister(type,fileName,picture.getPath()));
//              presenter.addUploadListener(uploadListener);
              presenter.uploadImageUrl(picture.getPath(), fileName);
			
           /* PictureDownloadUtils.getInstance().zipUpload(picture, fileName,true);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;//图片宽高都为原来的二分之一，即图片为原来的四分之一
            options.inTempStorage = new byte[100 * 1024];
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            options.inPurgeable = true;
            options.inInputShareable = true; */
           /* if(1 == type){
           	 idBeforePic = fileName;
           	  Bitmap b = FileSizeUtil.compressBitmap(picture.getPath(), faceButton.getWidth(), faceButton.getHeight());
           	  faceButton.setImageBitmap(b);
			 }else if(2 == type){
				 idAfterPic = fileName;
				  Bitmap b = FileSizeUtil.compressBitmap(picture.getPath(), backButton.getWidth(), backButton.getHeight());
				  backButton.setImageBitmap(b);
			 }else if(3 == type){
				 industryPic = fileName;
				 Bitmap b = FileSizeUtil.compressBitmap(picture.getPath(), otherButton.getWidth(), otherButton.getHeight());
				 otherButton.setImageBitmap(b);
			 }*/
        }
		
	}
	

	@Override
	public void onTwoAuthFailure(int errorCode, String errorMsg) {
		isClick = false;
	}

	@Override
	public void onTwoAuthSuccess() {
		Notification.toast(this, "上传成功");
		isClick = false;
		finish();
	}

	/**
	 * 选择图片弹出框
	 */
	private void showRealase() {
		dialog = new Dialog(this, R.style.custom_Dialog);
		Window win = dialog.getWindow();
		win.getDecorView().setPadding(0, 0, 0, 0);
		win.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
		WindowManager.LayoutParams lp = win.getAttributes();
		lp.width = WindowManager.LayoutParams.MATCH_PARENT;
		lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		win.setAttributes(lp);
		win.setWindowAnimations(R.style.buttom_animation);
		View view = LayoutInflater.from(this).inflate(R.layout.picture_select,null);
		photoBtn = (Button) view.findViewById(R.id.btn_take_photo);
		choosePicBtn = (Button) view.findViewById(R.id.btn_pick_photo);
		cancel_dialog = (Button) view.findViewById(R.id.btn_cancel);
		photoBtn.setOnClickListener(this);
		choosePicBtn.setOnClickListener(this);
		cancel_dialog.setOnClickListener(this);
		dialog.setContentView(view);
		dialog.setCancelable(true);
		dialog.show();
	}


	@Override
	public void onTwoAuthDetailFailure(int errorCode, String errorMsg) {
		Notification.toast(this, errorMsg);
	}

	@Override
	public void onTwoAuthDetailSuccess(TwoAuthDetailData data) {
		if(null != data){
			idBeforePic = data.getIdBeforePic();
			idAfterPic = data.getIdAfterPic();
			industryPic = data.getIndustryPic();
			status = data.getStatus();
			if(STATUS_PENDING == status){
				submitBtn.setText("待审批");
				submitBtn.setClickable(false);
				submitBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
			}else if(STATUS_PASS == status){
				GlobalContext.isIndustryAuthority = true;
				submitBtn.setText("审批通过");
				submitBtn.setClickable(false);
				submitBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
			}else if(STATUS_NO_PASS == status){
				Id = data.getId();
				submitBtn.setText("审批不通过(点击重新上传)");
				submitBtn.setClickable(true);
			}else{
				submitBtn.setText("确认上传");
				submitBtn.setClickable(true);
			}
			if(null != idBeforePic){
				showImage(idBeforePic, faceButton);
			}
			if(null != idAfterPic){
				showImage(idAfterPic, backButton);
			}
			if(null != industryPic){
				showImage(industryPic, otherButton);
			}
			
		}
	}
	
	private void showImage(String url,final ImageView image){
		url = GlobalContext.cdndownUrl + url;
		Glide.with(this)
		.load(url)
		.into(image);
	}
	
	/**
     * 打开图片查看器
     * 
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(this, position, urls2);
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	if(null != pDialog && pDialog.isShowing()){
			pDialog.dismiss();
		}
    }
//    /**
//	 * 上传图片事件监听
//	 */
//	UploadListener uploadListener = new UploadListener() {
//
//		@Override
//		public void onUploading(UploadTask uploadTask) {
//			// TODO Auto-generated method stub
//			System.out.println("正在上传");
//		}
//
//		@Override
//		public void onUploadFailed(UploadTask uploadTask, FailReason failReason) {
//			// TODO Auto-generated method stub
//			if(null != pDialog && pDialog.isShowing()){
//				pDialog.dismiss();
//			}
//			Notification.toast(IndustryAuthActivity.this, "上传失败" + failReason.toString());
//			UploadTask.Result result = uploadTask.getResult();
//			String requestId = (null==result ? "null" : result.requestId);
//			Log.e("IndustryAuthActivity", "###########onUploadFailed:" + requestId);
//			if (1 == type) {
//
//			} else if (2 == type) {
//
//			} else if (3 == type) {
//
//			}
//		}
//
//		@Override
//		public void onUploadComplete(UploadTask arg0) {
//			System.out.println("上传完成");
//			if(null != pDialog && pDialog.isShowing()){
//				pDialog.dismiss();
//			}
//		}
//
//		@Override
//		public void onUploadCancelled(UploadTask arg0) {
//			if(null != pDialog && pDialog.isShowing()){
//				pDialog.dismiss();
//			}
//		}
//	};
	
	class MyuploadLister implements UploadListener{

		private int type;
		private String fileName;
		private String pathImage;
		public MyuploadLister(int type,String fileName,String pathImage) {
			this.type = type;
			this.fileName = fileName;
			this.pathImage = pathImage;
		}
		
		@Override
		public void onUploadCancelled(UploadTask uploadTask) {
			// TODO Auto-generated method stub
			if(null != pDialog && pDialog.isShowing()){
				pDialog.dismiss();
			}
		}

		@Override
		public void onUploadComplete(UploadTask uploadTask) {
			System.out.println("上传完成");
			if(null != pDialog && pDialog.isShowing()){
				pDialog.dismiss();
			}
			  System.out.println("h:" + System.currentTimeMillis());
			 if(1 == type){
            	 idBeforePic = fileName;
            	 Bitmap b = FileSizeUtil.compressBitmap(pathImage, faceButton.getWidth(), faceButton.getHeight());
            	  faceButton.setImageBitmap(b);
			 }else if(2 == type){
				 idAfterPic = fileName;
				  Bitmap b = FileSizeUtil.compressBitmap(pathImage, backButton.getWidth(), backButton.getHeight());
				  backButton.setImageBitmap(b);
			 }else if(3 == type){
				 industryPic = fileName;
				 Bitmap b = FileSizeUtil.compressBitmap(pathImage, otherButton.getWidth(), otherButton.getHeight());
				 otherButton.setImageBitmap(b);
			 }
			  System.out.println("i:" + System.currentTimeMillis());
		}

		@Override
		public void onUploadFailed(UploadTask uploadTask, FailReason failReason) {
			// TODO Auto-generated method stub
			if(null != pDialog && pDialog.isShowing()){
				pDialog.dismiss();
			}
			Notification.toast(IndustryAuthActivity.this, "上传失败" + failReason.toString());
			UploadTask.Result result = uploadTask.getResult();
			String requestId = (null==result ? "null" : result.requestId);
			Log.e("IndustryAuthActivity", "###########onUploadFailed:" + requestId );
			 if(1 == type){
				 idBeforePic = "";
            	  faceButton.setImageBitmap(null);
			 }else if(2 == type){
				 idAfterPic = "";
				  backButton.setImageBitmap(null);
			 }else if(3 == type){
				 industryPic = "";
				 otherButton.setImageBitmap(null);
			 }
		}

		@Override
		public void onUploading(UploadTask uploadTask) {
			// TODO Auto-generated method stub
			System.out.println("正在上传");
		}
		
	}
	
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
}
